import React, { useState, useEffect } from 'react';
import styles from './styles.module.css';

export interface MessageProps {
  type: 'success' | 'error' | 'warning' | 'info';
  message: string;
  duration?: number;
  onClose?: () => void;
  visible: boolean;
}

const Message: React.FC<MessageProps> = ({
  type,
  message,
  duration = 3000,
  onClose,
  visible
}) => {
  const [isVisible, setIsVisible] = useState(visible);

  useEffect(() => {
    setIsVisible(visible);
  }, [visible]);

  useEffect(() => {
    if (isVisible && duration > 0) {
      const timer = setTimeout(() => {
        setIsVisible(false);
        onClose?.();
      }, duration);

      return () => clearTimeout(timer);
    }
  }, [isVisible, duration, onClose]);

  const handleClose = () => {
    setIsVisible(false);
    onClose?.();
  };

  if (!isVisible) return null;

  const getIcon = () => {
    switch (type) {
      case 'success':
        return '✓';
      case 'error':
        return '✕';
      case 'warning':
        return '⚠';
      case 'info':
        return 'ℹ';
      default:
        return '';
    }
  };

  return (
    <div className={`${styles.message} ${styles[type]}`}>
      <div className={styles.messageContent}>
        <span className={styles.messageIcon}>{getIcon()}</span>
        <span className={styles.messageText}>{message}</span>
        <button
          className={styles.closeButton}
          onClick={handleClose}
          aria-label="关闭消息"
        >
          ×
        </button>
      </div>
    </div>
  );
};

export default Message;